﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;
using BLL.Access;
using DevExpress.Web;
using Entity;

namespace Web.Class
{
    public class PageTools
    {
        /// <summary>
        ///     导出文件格式
        /// </summary>
        public enum eExportFileType
        {
            Excel,
            txt
        }

        /// <summary>
        ///     下拉框数据类别
        /// </summary>
        public enum eLoadType
        {
            站点,
            管理块,
            业务员,
            局,
            行政区,
            用水性质,
            行业类型,
            考核复用,
            部门,
            管理部门QS,
            行政区QS,
            业务员QS,
            环线标记QS,
            取水用途QS,
            行业分类QS,
            流域QS,
            水利分片QS,
            水资源分区QS,
            井类型QS,
            井性质QS,
            费用类型QS,
            退款类型QS,
            井标记QS,
            水量类别QS
        }


        /// <summary>
        ///     验证字符串规则
        /// </summary>
        public enum eValidateType
        {
            数字,
            正数,
            带两位小数,
            用户号,
            水价,
            正浮点数
        }


        /// <summary>
        ///     绑定下拉框
        /// </summary>
        /// <param name="cmbBox"></param>
        /// <param name="dt"></param>
        public static void BindComboBox(ASPxComboBox cmbBox, DataTable dt)
        {
            if (dt.Columns.Contains("WORDSCONTENT"))
            {
                cmbBox.TextField = "WORDSCONTENT";
                cmbBox.ValueField = "WORDSVALUE";
            }
            else
            {
                cmbBox.TextField = "TEXT";
                cmbBox.ValueField = "VALUE";
            }
            cmbBox.DataSource = dt;
            cmbBox.DataBind();
        }

        /// <summary>
        ///     绑定下拉框
        /// </summary>
        /// <param name="cmbBox"></param>
        /// <param name="dt"></param>
        public static void BindComboBox(ASPxComboBox cmb, DataTable dt, string all)
        {
            if (dt.Columns.Contains("WORDSCONTENT"))
            {
                cmb.TextField = "WORDSCONTENT";
                cmb.ValueField = "WORDSVALUE";
            }
            else
            {
                cmb.TextField = "TEXT";
                cmb.ValueField = "VALUE";
            }
            var drTemp = dt.NewRow();
            drTemp[0] = all == null ? "" : all;
            drTemp[1] = "-1";
            dt.Rows.InsertAt(drTemp, 0);
            BindComboBox(
                cmb, dt
            );
            cmb.DataSource = dt;
            cmb.DataBind();
            if (cmb.Items.Count > 0)
                cmb.SelectedIndex = 0;
        }

        /// <summary>
        ///     根据数据源中的某列去匹配指定的值 并定位到GRIDVIEW记录并返回该条记录的ID
        /// </summary>
        /// <param name="dtSource">数据源</param>
        /// <param name="gv">gridview</param>
        /// <param name="matchColumn">要匹配的列</param>
        /// <param name="matchValue">要匹配的值</param>
        public static int FocusOpreateRecord(DataTable dtSource, ASPxGridView gv, string matchColumn, string matchValue,
            bool exact)
        {
            var findIndex = -1;
            var id = -1;
            for (var i = 0; i < dtSource.Rows.Count; i++)
                if (matchColumn.ToLower() == "index")
                {
                    findIndex = int.Parse(matchValue);
                }
                else
                {
                    if (exact)
                    {
                        if (Convert.ToString(dtSource.Rows[i][matchColumn]) == matchValue)
                        {
                            findIndex = i;
                            if (dtSource.Columns.Contains("ID"))
                                id = Convert.ToInt32(dtSource.Rows[i]["ID"]);
                            else
                                id = Convert.ToInt32(dtSource.Rows[i][matchColumn]);
                            break;
                        }
                    }
                    else
                    {
                        if (Convert.ToString(dtSource.Rows[i][matchColumn]).Replace(" ", "")
                            .Contains(matchValue.Replace(" ", "")))
                        {
                            findIndex = i;
                            if (dtSource.Columns.Contains("ID"))
                                id = Convert.ToInt32(dtSource.Rows[i]["ID"]);
                            else
                                id = Convert.ToInt32(dtSource.Rows[i][matchColumn]);
                            break;
                        }
                    }
                }
            gv.FocusedRowIndex = findIndex;
            gv.ScrollToVisibleIndexOnClient = findIndex;
            return id;
        }

        /// <summary>
        ///     根据数据源中的某列去匹配指定的值 并定位到GRIDVIEW记录并返回该条记录的ID
        /// </summary>
        /// <param name="dtSource">数据源</param>
        /// <param name="gv">gridview</param>
        /// <param name="matchColumn">要匹配的列</param>
        /// <param name="matchValue">要匹配的值</param>
        public static int FocusOpreateRecord(DataTable dtSource, string matchColumn, string matchValue,
            bool exact)
        {
            var findIndex = -1;
            var id = -1;
            for (var i = 0; i < dtSource.Rows.Count; i++)
                if (matchColumn.ToLower() == "index")
                {
                    findIndex = int.Parse(matchValue);
                }
                else
                {
                    if (exact)
                    {
                        if (Convert.ToString(dtSource.Rows[i][matchColumn]) == matchValue)
                        {
                            findIndex = i;
                            if (dtSource.Columns.Contains("ID"))
                                id = Convert.ToInt32(dtSource.Rows[i]["ID"]);
                            else
                                id = Convert.ToInt32(dtSource.Rows[i][matchColumn]);
                            break;
                        }
                    }
                    else
                    {
                        if (Convert.ToString(dtSource.Rows[i][matchColumn]).Replace(" ", "")
                            .Contains(matchValue.Replace(" ", "")))
                        {
                            findIndex = i;
                            if (dtSource.Columns.Contains("ID"))
                                id = Convert.ToInt32(dtSource.Rows[i]["ID"]);
                            else
                                id = Convert.ToInt32(dtSource.Rows[i][matchColumn]);
                            break;
                        }
                    }
                } 
            return findIndex;
        }

        /// <summary>
        ///     根据数据源中的某列去匹配指定的值 并定位到GRIDVIEW记录并返回该条记录在位置
        /// </summary>
        /// <param name="dtSource">数据源</param>
        /// <param name="gv">gridview</param>
        /// <param name="matchColumn">要匹配的列</param>
        /// <param name="matchValue">要匹配的值</param>
        public static int SearchRecordIndex(DataTable dtSource, ASPxGridView gv, string matchColumn, string matchValue,
            bool exact)
        {
            var findIndex = -1;
            if (dtSource != null)
                for (var i = 0; i < dtSource.Rows.Count; i++)
                    if (exact)
                    {
                        if (Convert.ToString(dtSource.Rows[i][matchColumn]) == matchValue)
                        {
                            findIndex = i;
                            break;
                        }
                    }
                    else
                    {
                        if (Convert.ToString(dtSource.Rows[i][matchColumn]).Replace(" ", "")
                            .Contains(matchValue.Replace(" ", "")))
                        {
                            findIndex = i;
                            break;
                        }
                    }
            return findIndex;
        }

        /// <summary>
        ///     根据数据源中的某列去匹配指定的值 并定位到GRIDVIEW记录并返回该条记录在位置
        /// </summary>
        /// <param name="dtSource">数据源</param>
        /// <param name="gv">gridview</param>
        /// <param name="matchColumn">要匹配的列</param>
        /// <param name="matchValue">要匹配的值</param>
        public static int SearchRecordIndex(ASPxGridView gv, string matchColumn, string matchValue, bool exact)
        {
            var findIndex = -1;
            for (var i = 0; i < gv.VisibleRowCount; i++)
                if (exact)
                {
                    if (Convert.ToString(gv.GetRowValues(i, matchColumn)) == matchValue)
                    {
                        findIndex = i;
                        break;
                    }
                }
                else
                {
                    if (Convert.ToString(gv.GetRowValues(i, matchColumn)).Replace(" ", "")
                        .Contains(matchValue.Replace(" ", "")))
                    {
                        findIndex = i;
                        break;
                    }
                }
            return findIndex;
        }

        public static void AlertMsg(Control cotrol, string msg)
        {
            var text = default(Guid).ToString();
            ScriptManager.RegisterClientScriptBlock(cotrol, cotrol.GetType(), text,
                new StringBuilder("window.alert('").Append(msg).Append("');").ToString(), true);
        }

        public static void AlertMsg(Control cotrol, string msg, string script)
        {
            var text = default(Guid).ToString();
            ScriptManager.RegisterClientScriptBlock(cotrol, cotrol.GetType(), text,
                new StringBuilder("window.alert('").Append(msg).Append("');" + script + "").ToString(), true);
        }

        public static void ResponseScript(Control cotrol, string script)
        {
            var text = default(Guid).ToString();
            ScriptManager.RegisterClientScriptBlock(cotrol, cotrol.GetType(), text,
                new StringBuilder(script).ToString(), true);
        }

        /// <summary>
        ///     提示确认框,前台页面需要放置asp:HiddenField ID="confirmValue" runat="server"
        ///     及asp:Button ID="btnDelFact" runat="server" Text="Button" OnClick="btnDelFact_Click" Visible="false"
        /// </summary>
        /// <param name="cotrol">this</param>
        /// <param name="msg">要弹得提示消息</param>
        public static void ConfirmMsg(Control cotrol, string msg)
        {
            var text = "if(confirm('" + msg +
                       "')){document.getElementById('confirmValue').value=true;}else{document.getElementById('confirmValue').value=false};document.getElementById('btnDelFact').click();";

            ScriptManager.RegisterClientScriptBlock(cotrol, cotrol.GetType(), default(Guid).ToString(), text, true);
        }

        /// <summary>
        ///     提示确认框,前台页面需要放置asp:HiddenField ID="confirmValue" runat="server"
        ///     及asp:Button ID="btnDelFact" runat="server" Text="Button" OnClick="btnDelFact_Click" Visible="false"
        /// </summary>
        /// <param name="cotrol">this</param>
        /// <param name="msg">要弹得提示消息</param>
        public static void ConfirmMsg(Control cotrol, string msg, string btn)
        {
            var text = "if(confirm('" + msg +
                       "')){document.getElementById('confirmValue').value=true;}else{document.getElementById('confirmValue').value=false};document.getElementById('" +
                       btn + "').click();";

            ScriptManager.RegisterClientScriptBlock(cotrol, cotrol.GetType(), default(Guid).ToString(), text, true);
        }

        /// <summary>
        ///     验证字符
        /// </summary>
        /// <param name="str">要验证的字符串</param>
        /// <returns>返回真或假</returns>
        public static bool ValidateString(string str, eValidateType vType)
        {
            Regex reg1 = null;
            if (vType == eValidateType.数字)
                reg1 = new Regex(@"^[0-9]+$");
            else if (vType == eValidateType.正数)
                reg1 = new Regex(@"^[0-9]+\.?[0-9]{0,9}$");
            else if (vType == eValidateType.正浮点数)
                reg1 = new Regex(@"^[1-9]\d*\.\d*|0\.\d*[1-9]\d*$");
            else if (vType == eValidateType.带两位小数)
                reg1 = new Regex(@"^\d+(\.\d{2})+$");
            else if (vType == eValidateType.用户号)
                reg1 = new Regex(@"^\d+(\.\d{2})+$");

            else if (vType == eValidateType.水价)
                reg1 = new Regex(@"^\d+(.\d{1,2})?$");
            return reg1.IsMatch(str);
        }

        /// <summary>
        ///     普通格式导出
        /// </summary>
        public static void CreateExcel(DataTable dt, string fileName)
        {
            var resp = HttpContext.Current.Response;
            resp.ContentType = "application/ms-excel";
            resp.Charset = "UTF-8";
            resp.ContentEncoding = Encoding.GetEncoding("GB2312");
            resp.AppendHeader("Content-Disposition",
                "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8));
            var sw = new StringWriter();
            var str = new StringBuilder();
            for (var i = 0; i < dt.Columns.Count; i++)
                str.Append(dt.Columns[i].Caption).Append("\t");
            sw.WriteLine(str.ToString());
            //逐行处理数据   
            foreach (DataRow row in dt.Rows)
            {
                str.Clear();
                //当前行数据写入HTTP输出流，并且置空ls_item以便下行数据     
                for (var j = 0; j < dt.Columns.Count; j++)
                    str.Append(row[j]).Append("\t");
                sw.WriteLine(str.ToString());
            }
            sw.Close();
            resp.Write(sw);
            resp.End();
        }

        /// <summary>
        ///     处理前面带有0的用户号
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="fileName"></param>
        public static void CreateExcel3(DataTable dt, string fileName)
        {
            var resp = HttpContext.Current.Response;
            resp.ContentType = "application/ms-excel";
            resp.Charset = "UTF-8";
            resp.ContentEncoding = Encoding.GetEncoding("GB2312");
            resp.AppendHeader("Content-Disposition",
                "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8));
            var sw = new StringWriter();
            var str = new StringBuilder();
            for (var i = 0; i < dt.Columns.Count; i++)
                if (i == 0)
                    str.Append(dt.Columns[i].Caption).Append("\t");
                else
                    str.Append(dt.Columns[i].Caption).Append("\t");
            sw.WriteLine(str.ToString());
            //逐行处理数据   
            foreach (DataRow row in dt.Rows)
            {
                str.Clear();
                //当前行数据写入HTTP输出流，并且置空ls_item以便下行数据     
                for (var j = 0; j < dt.Columns.Count; j++)
                    str.Append(row[j]).Append("\t");
                sw.WriteLine(str.ToString());
            }
            sw.Close();
            resp.Write(sw);
            resp.End();
        }

        public static void ExportExcel(DataTable dt)
        {
            var fileName = "导出文件" + DateTime.Now.ToString("yyyy-MM-dd") + ".xlsx";
            var resp = HttpContext.Current.Response;
            resp.ContentType = "application/ms-excel";
            resp.Charset = "UTF-8";
            //resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            resp.AppendHeader("Content-Disposition",
                "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8));
            var sw = new StringWriter();
            var str = new StringBuilder();
            for (var i = 0; i < dt.Columns.Count; i++)
                str.Append(dt.Columns[i].Caption).Append("\t");
            sw.WriteLine(str.ToString());
            //逐行处理数据   
            foreach (DataRow row in dt.Rows)
            {
                str.Clear();
                //当前行数据写入HTTP输出流，并且置空ls_item以便下行数据     
                for (var j = 0; j < dt.Columns.Count; j++)
                    str.Append(row[j]).Append("\t");
                sw.WriteLine(str.ToString());
            }
            sw.Close();
            resp.Write(sw);
            resp.End();
        }

        /// <summary>
        ///     按html table格式导出
        /// </summary>
        public static void CreateExcel2(DataTable dt, string fileName)
        {
            var resp = HttpContext.Current.Response;
            resp.ContentType = "application/ms-excel";
            resp.Charset = "UTF-8";
            //resp.ToString = "@";
            resp.ContentEncoding = Encoding.GetEncoding("GB2312");
            resp.AppendHeader("Content-Disposition",
                "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8));
            var str = new StringBuilder();
            str.Append("<table border=\"1px\" style=\"font-size:10pt\">");
            str.Append("<tr style=\"background-color:yellow;\">");
            for (var i = 0; i < dt.Columns.Count; i++)
                str.Append("<td align=\"center\"><b>").Append(dt.Columns[i].Caption).Append("</b></td>");
            str.Append("</tr>");
            //逐行处理数据   
            foreach (DataRow row in dt.Rows)
            {
                str.Append("<tr>");
                //当前行数据写入HTTP输出流，并且置空ls_item以便下行数据     
                for (var j = 0; j < dt.Columns.Count; j++)
                    str.Append("<td align=\"center\">").Append(row[j]).Append("</td>");
                str.Append("</tr>");
            }

            str.Append("</table>");
            resp.Write(str.ToString());
            resp.End();
        }

        public static void CreateExcelAccordWidths(DataTable dt, List<string> columnwidths, string fileName)
        {
            var resp = HttpContext.Current.Response;
            resp.ContentType = "application/ms-excel";
            resp.Charset = "UTF-8";
            resp.ContentEncoding = Encoding.GetEncoding("GB2312");
            resp.AppendHeader("Content-Disposition",
                "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8));
            var str = new StringBuilder();
            str.Append("<table border=\"1px\" style=\"font-size:10pt;color:gray;\">");
            str.Append("<tr>");
            for (var i = 0; i < dt.Columns.Count; i++)
                str.Append("<td align=\"center\" style=\"width:" + columnwidths[i] + ";\"><b>")
                    .Append(dt.Columns[i].Caption).Append("</b></td>");
            str.Append("</tr>");
            //逐行处理数据   
            foreach (DataRow row in dt.Rows)
            {
                str.Append("<tr>");
                //当前行数据写入HTTP输出流，并且置空ls_item以便下行数据     
                for (var j = 0; j < dt.Columns.Count; j++)
                    str.Append("<td align=\"center\">").Append(row[j]).Append("</td>");
                str.Append("</tr>");
            }
            str.Append("</table>");
            resp.Write(str.ToString());
            resp.End();
        }

        public static void CreateTxt(DataTable dt, string fileName)
        {
            var resp = HttpContext.Current.Response;
            resp.ContentType = "text/plain;charset=gb2312";
            //resp.Charset = "UTF-8";
            resp.ContentEncoding = Encoding.GetEncoding("gb2312"); //注意编码
            resp.AppendHeader("Content-Disposition",
                "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.GetEncoding("gb2312")));
            var str = new StringBuilder();
            var sw = new StringWriter();
            //逐行处理数据   
            foreach (DataRow row in dt.Rows)
            {
                str.Clear();
                //str.Append(row[0]).Append("\t");
                str.Append(row[0]);
                sw.WriteLine(str.ToString());
            }
            sw.Close();
            resp.Write(sw);
            resp.End();
        }


        ///// <summary>
        ///// 导出excel
        ///// </summary>
        ///// <param name="dt"></param>
        //public static void ExportExcel(DataTable dt)
        //{
        //    //创建Excel对象

        //    Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
        //    excel.Application.Workbooks.Add(true);
        //    excel.Visible = true;
        //    //生成字段，即添加表头
        //    for (int i = 0; i < dt.Columns.Count; i++)
        //    {
        //        excel.Cells[1, i + 1] = dt.Columns[i].ColumnName;
        //    }
        //    //填充内容
        //    for (int i = 0; i < dt.Rows.Count; i++)
        //    {
        //        for (int j = 0; j < dt.Columns.Count; j++)
        //        {
        //            if (dt.Rows[i][j] == null)
        //            {
        //                excel.Cells[i + 2, j + 1] = "";
        //            }
        //            else
        //            {
        //                excel.Cells[i + 2, j + 1] = dt.Rows[i][j].ToString();
        //            }
        //        }
        //    }

        //}

        /// <summary>
        ///     以流的形式，可以设置很丰富复杂的样式
        /// </summary>
        /// <param name="content">Excel中内容(Table格式)</param>
        /// <param name="filename">文件名</param>
        /// <param name="cssText">样式内容</param>
        public static void ExportToExcel(string filename, string content, string cssText)
        {
            var res = HttpContext.Current.Response;
            content = string.Format("<style type='text/css'>{0}</style>{1}", cssText, content);

            res.Clear();
            res.Buffer = true;
            res.Charset = "UTF-8";
            res.AddHeader("Content-Disposition", "attachment; filename=" + filename);
            res.ContentEncoding = Encoding.GetEncoding("UTF-8");
            res.ContentType = "application/ms-excel;charset=UTF-8";
            res.Write(content);
            res.Flush();
            res.End();
        }

        /// <summary>
        ///     将文本框设置为不可编辑状态,此种状态可正常使用Textbox前端方法GetText(),SetText()等
        /// </summary>
        /// <param name="tb">要设置的文本框</param>
        /// <param name="setOrRemove">true:set  flase:remove</param>
        public static void SetDisabled(ASPxTextBox tb, bool setOrRemove)
        {
            if (setOrRemove)
                tb.Attributes.Add("disabled", "disabled");
            else
                tb.Attributes.Remove("disabled");
        }

        /// <summary>
        ///     将文本框设置为不可编辑状态,此种状态可正常使用Textbox前端方法GetText(),SetText()等
        /// </summary>
        /// <param name="tb">要设置的文本框</param>
        /// <param name="setOrRemove">true:set  flase:remove</param>
        public static void SetDisabled(ASPxCheckBox tb, bool setOrRemove)
        {
            if (setOrRemove)
            {
                tb.Attributes.Add("disabled", "disabled");
                tb.ForeColor = Color.FromName("#c0c0c0");
                //tb.Style.Add("ForeColor", "#c0c0c0");
            }
            else
            {
                tb.Attributes.Remove("disabled");
                tb.ForeColor = Color.Black;
            }
        }

        /// <summary>
        ///     将文本框设置为不可编辑状态,此种状态可正常使用Textbox前端方法GetText(),SetText()等
        /// </summary>
        /// <param name="tb">要设置的文本框</param>
        /// <param name="setOrRemove">true:set  flase:remove</param>
        public static void SetDisabled(ASPxComboBox tb, bool setOrRemove)
        {
            if (setOrRemove)
            {
                tb.Attributes.Add("disabled", "disabled");
                tb.ForeColor = Color.FromName("#c0c0c0");
                //tb.Style.Add("ForeColor", "#c0c0c0");
            }
            else
            {
                tb.Attributes.Remove("disabled");
                tb.ForeColor = Color.Black;
            }
        }

        /// <summary>
        ///     加载站点下的管理块/业务员
        /// </summary>
        /// <param name="cmb">下拉框</param>
        /// <param name="type">要加载的类型</param>
        /// <param name="zhandianbh">站点</param>
        /// <param name="spit">分隔符</param>
        /// <param name="all">空选项文本</param>
        public static void LoadCombox(ASPxComboBox cmb, eLoadType type, string zhandianbh, string spit, string all)
        {
            zhandianbh = BusinessTool.ZHANDIANBH();
            var dcRoles = new Dictionary<string, string>();
            var drc = BusinessTool.GetTextAndValue(
                "View_AS_UserInfo", "ROLENAME", "ROLEID", null, "userid=" + LoginInfo.CurrentUser.UserID
            ).Tables[0].Rows;
            for (var i = 0; i < drc.Count; i++)
                dcRoles.Add(Convert.ToString(drc[i]["VALUE"]), Convert.ToString(drc[i]["TEXT"]));
            //获取当前登录人角色
            //string rolename= BLL.BusinessTool.GetTextAndValue(
            //           "View_AS_UserInfo", "ROLENAME", "ROLEID", null, "userid=" + LoginInfo.CurrentUser.UserID 
            //       ).Tables[0].Rows[0]["TEXT"].ToString();
            string conzd = null;
            string conywy = null;
            if (dcRoles.ContainsValue("主任") || dcRoles.ContainsValue("业务员"))
                conzd = " ZHANDIANBH='" + zhandianbh + "'";
            //if (rolename.Contains("主任") ||rolename.Contains("业务员"))
            //{
            //    conzd = " ZHANDIANBH='" + zhandianbh + "'";
            //}
            if (!dcRoles.ContainsValue("业务员"))
                conywy = "ROLENAME like '%业务员%'";
            else
                conywy = "ROLENAME like '%业务员%' and userid=" + LoginInfo.CurrentUser.UserID;
            DataTable dt;
            if (type == eLoadType.站点)
            {
                dt = BusinessTool.GetTextAndValue(
                    "YS_JX_ZHANDIAN", "S_ZHANDIANMC", "S_ZHANDIANBH", spit,
                    zhandianbh == "00" ? "S_ZHANDIANBH<>00" : "S_ZHANDIANBH=" + zhandianbh
                ).Tables[0];
            }
            else if (type == eLoadType.管理块)
            {
                dt = BusinessTool.GetTextAndValue(
                    "YS_JX_GUANLIK", "S_GUANLIKMC", "S_GUANLIKH", spit,
                    "I_JLZT=0 AND "+(zhandianbh == "00" ? "S_ZHANDIAN<>00" : "S_ZHANDIAN=" + zhandianbh)
                ).Tables[0];
            }
            else if (type == eLoadType.业务员)
            {
                dt = new SpHelper().P_COMMON_YWYGET(BusinessTool.WType, spit,
                    conywy + (conzd == null ? "" : " and " + conzd), null).Tables[0];
                //dt = BLL.BusinessTool.GetTextAndValue(
                //    "View_AS_UserInfo", "USERNAME", "USERID", spit, conywy + (conzd == null ? "" : " and " + conzd)
                //   ).Tables[0];
            }
            else if (type == eLoadType.行业类型)
            {
                dt = BusinessTool.GetTextAndValue(
                    "YS_JX_HANGYELX", "S_SHESHUIDXFLMC", "S_SHESHUIDXFLDM", spit, null
                ).Tables[0];
            }
            else if (type == eLoadType.行政区)
            {
                dt = BusinessTool.GetTextAndValue(
                    "YS_JX_XINGZHENGQ", "S_MINGCHENG", "S_BIANHAO", spit, "I_JLZT=0"
                ).Tables[0];
            }
            else if (type == eLoadType.局)
            {
                dt = BusinessTool.GetTextAndValue(
                    "YS_JX_JUXINX", "S_MINGCHENG", "S_BIANHAO", spit,
                    "I_LEIXING=1 AND " + (zhandianbh == "00" ? "S_ZHANDIANBH<>00" : "S_ZHANDIANBH=" + zhandianbh)
                ).Tables[0];
            }
            else if (type == eLoadType.用水性质)
            {
                //获取站点名称

                var dr = new YS_JX_ZHANDIANBLL().SelectYS_JX_ZHANDIANsDynamic("S_ZHANDIANBH=" + zhandianbh, null)
                    .Rows[0];
                var zhandianmc = dr["S_ZHANDIANMC"].ToString();
                dt = BusinessTool.GetTextAndValue(
                    "YS_JX_YONGSHUIXZ", "S_MINGCHENG", "S_BIANMA", null,
                    string.Format("I_TYPE={0}", zhandianmc.Contains("本部") ? 1 : 0)
                ).Tables[0];
            }
            else if (type == eLoadType.考核复用)
            {
                dt = new WordsManager().Instance.FindWordsDataTableWithMiddleAffixByBelongID(WordsStruct.BelongID.考核复用,
                    spit);
            }
            else
            {
                dt = new DataTable();
            }
            if (all != null)
            {
                var drTemp = dt.NewRow();
                drTemp[0] = all;
                drTemp[1] = "-1";
                dt.Rows.InsertAt(drTemp, 0);
            }
            BindComboBox(
                cmb, dt
            );
            if (cmb.Items.Count > 0)
                cmb.SelectedIndex = 0;
        }

        /// <summary>
        ///     加载下拉框,与站点无关
        /// </summary>
        /// <param name="cmb"></param>
        /// <param name="type"></param>
        /// <param name="spit"></param>
        /// <param name="all"></param>
        public static void LoadCombox2(ASPxComboBox cmb, eLoadType type, string spit, string all)
        {
            DataTable dt;
            if (type == eLoadType.站点)
                dt = BusinessTool.GetTextAndValue(
                    "YS_JX_ZHANDIAN", "S_ZHANDIANMC", "S_ZHANDIANBH", spit, null
                ).Tables[0];
            else if (type == eLoadType.管理块)
                dt = BusinessTool.GetTextAndValue(
                    "YS_JX_GUANLIK", "S_GUANLIKMC", "S_GUANLIKH", spit, null
                ).Tables[0];
            else if (type == eLoadType.业务员)
                dt = BusinessTool.GetTextAndValue(
                    "View_AS_UserInfo", "USERNAME", "USERID", spit, null
                ).Tables[0];
            else if (type == eLoadType.行业类型)
                dt = BusinessTool.GetTextAndValue(
                    "YS_JX_HANGYELX", "S_SHESHUIDXFLMC", "S_SHESHUIDXFLDM", spit, null
                ).Tables[0];
            else if (type == eLoadType.行政区)
                dt = BusinessTool.GetTextAndValue(
                    "YS_JX_XINGZHENGQ", "S_MINGCHENG", "S_BIANHAO", spit, null
                ).Tables[0];
            else if (type == eLoadType.局)
                dt = BusinessTool.GetTextAndValue(
                    "YS_JX_JUXINX", "S_MINGCHENG", "S_BIANHAO", spit, "I_LEIXING=1"
                ).Tables[0];
            else if (type == eLoadType.用水性质)
                dt = BusinessTool.GetTextAndValue(
                    "YS_JX_YONGSHUIXZ", "S_MINGCHENG", "S_BIANMA", spit, null
                ).Tables[0];
            else if (type == eLoadType.考核复用)
                dt = new WordsManager().Instance.FindWordsDataTableWithMiddleAffixByBelongID(WordsStruct.BelongID.考核复用,
                    spit);
            else if (type == eLoadType.部门)
                dt = BusinessTool.GetTextAndValue(
                    "YS_JX_BUMENXX", "S_MINGCHENG", "S_BIANHAO", spit, null
                ).Tables[0];
            else
                dt = new DataTable();
            if (all != null)
            {
                var drTemp = dt.NewRow();
                drTemp[0] = all;
                drTemp[1] = "-1";
                dt.Rows.InsertAt(drTemp, 0);
            }
            BindComboBox(
                cmb, dt
            );
            if (cmb.Items.Count > 0)
                cmb.SelectedIndex = 0;
        }

        /// <summary>
        ///     用于功能性操作绑定业务员等(如开户)
        /// </summary>
        public static void LoadCombox(ASPxComboBox cmb, eLoadType type, bool isSearch, string spit, string all)
        {
            //获取当前登录人角色
            //string rolename = BLL.BusinessTool.GetTextAndValue(
            //           "View_AS_UserInfo", "ROLENAME", "ROLEID", null, "userid=" + LoginInfo.CurrentUser.UserID
            //       ).Tables[0].Rows[0]["TEXT"].ToString();
            string conzd = null;
            string conywy = null;
            var zhandianbh = BusinessTool.ZHANDIANBH();
            var dcRoles = new Dictionary<string, string>();
            var drc = BusinessTool.GetTextAndValue(
                "View_AS_UserInfo", "ROLENAME", "ROLEID", null, "userid=" + LoginInfo.CurrentUser.UserID
            ).Tables[0].Rows;
            for (var i = 0; i < drc.Count; i++)
                dcRoles.Add(Convert.ToString(drc[i]["VALUE"]), Convert.ToString(drc[i]["TEXT"]));
            if (zhandianbh != "00")
                conzd = " ZHANDIANBH='" + zhandianbh + "'";
            if (!dcRoles.ContainsValue("业务员"))
                conywy = "ROLENAME like '%业务员%' AND ROLEID=9001";
            else
                conywy = "ROLENAME like '%业务员%' AND ROLEID=9001 and userid=" + LoginInfo.CurrentUser.UserID;
            DataTable dt;
            if (type == eLoadType.站点)
            {
                dt = BusinessTool.GetTextAndValue(
                    "YS_JX_ZHANDIAN", "S_ZHANDIANMC", "S_ZHANDIANBH", spit,
                    zhandianbh == "00" ? "S_ZHANDIANBH<>00" : "S_ZHANDIANBH=" + zhandianbh
                ).Tables[0];
            }
            else if (type == eLoadType.管理块)
            {
                dt = BusinessTool.GetTextAndValue(
                    "YS_JX_GUANLIK", "S_GUANLIKMC", "S_GUANLIKH", spit,
                    zhandianbh == "00" ? "S_ZHANDIAN<>00" : "S_ZHANDIAN=" + zhandianbh
                ).Tables[0];
            }
            else if (type == eLoadType.业务员)
            {
                dt = BusinessTool.GetTextAndValue(
                    "View_AS_UserInfo", "USERNAME", "USERID", spit, conywy + (conzd == null ? "" : " and " + conzd)
                ).Tables[0];
            }
            else if (type == eLoadType.行业类型)
            {
                dt = BusinessTool.GetTextAndValue(
                    "YS_JX_HANGYELX", "S_SHESHUIDXFLMC", "S_SHESHUIDXFLDM", spit, null
                ).Tables[0];
            }
            else if (type == eLoadType.行政区)
            {
                dt = BusinessTool.GetTextAndValue(
                    "YS_JX_XINGZHENGQ", "S_MINGCHENG", "S_BIANHAO", spit, null
                ).Tables[0];
            }
            else if (type == eLoadType.局)
            {
                dt = BusinessTool.GetTextAndValue(
                    "YS_JX_JUXINX", "S_MINGCHENG", "S_BIANHAO", spit,
                    "I_LEIXING=1 AND " + (zhandianbh == "00" ? "S_ZHANDIANBH<>00" : "S_ZHANDIANBH=" + zhandianbh)
                ).Tables[0];
            }
            else if (type == eLoadType.用水性质)
            {
                //获取站点名称

                var dr = new YS_JX_ZHANDIANBLL().SelectYS_JX_ZHANDIANsDynamic("S_ZHANDIANBH=" + zhandianbh, null)
                    .Rows[0];
                var zhandianmc = dr["S_ZHANDIANMC"].ToString();
                dt = BusinessTool.GetTextAndValue(
                    "YS_JX_YONGSHUIXZ", "S_MINGCHENG", "S_BIANMA", null,
                    string.Format("I_TYPE={0}", zhandianmc.Contains("本部") ? 1 : 0)
                ).Tables[0];
            }
            else if (type == eLoadType.考核复用)
            {
                dt = new WordsManager().Instance.FindWordsDataTableWithMiddleAffixByBelongID(WordsStruct.BelongID.考核复用,
                    spit);
            }
            else
            {
                dt = new DataTable();
            }
            if (all != null)
            {
                var drTemp = dt.NewRow();
                drTemp[0] = all;
                drTemp[1] = "-1";
                dt.Rows.InsertAt(drTemp, 0);
            }
            BindComboBox(
                cmb, dt
            );
            if (cmb.Items.Count > 0)
                cmb.SelectedIndex = 0;
        }

        /// <summary>
        ///     根据管理块加载用水性质
        /// </summary>
        /// <param name="cmb">用水性质下拉框</param>
        public static void LoadComboxYongShuiXZByGuanLiK(ASPxComboBox cmb, string glkbh, string spit, string all)
        {
            var dt = BusinessTool.GetTextAndValue(
                "YS_JX_YONGSHUIXZ", "S_MINGCHENG", "S_BIANMA", spit,
                string.Format("I_TYPE={0}", glkbh == "14" || glkbh == "15" ? 0 : 1)
            ).Tables[0];
            if (all != null)
            {
                var drTemp = dt.NewRow();
                drTemp[0] = all;
                drTemp[1] = "-1";
                dt.Rows.InsertAt(drTemp, 0);
            }
            BindComboBox(
                cmb, dt
            );
            if (cmb.Items.Count > 0)
                cmb.SelectedIndex = 0;
        }

        /// <summary>
        ///     加载局下公司
        /// </summary>
        /// <param name="cmb">下拉框</param>
        /// <param name="zhandianbh">局号</param>
        /// <param name="spit">分隔符</param>
        public static void LoadComboxGongSi(ASPxComboBox cmb, string jubh, string spit)
        {
            var dt = BusinessTool.GetTextAndValue(
                "YS_JX_GONGSIXX", "S_MINGCHENG", "S_BIANHAO", spit,
                string.Format("I_LEIXING=1 AND S_JUBIANH='{0}'", jubh)
            ).Tables[0];
            var drTemp = dt.NewRow();
            BindComboBox(
                cmb, dt
            );
            if (cmb.Items.Count > 0)
                cmb.SelectedIndex = 0;
        }

        /// <summary>
        ///     取水 用于功能性操作绑定业务员等
        /// </summary>
        public static void QSLoadCombox(ASPxComboBox cmb, eLoadType type, string spit, string all)
        {
            DataTable dt;
            if (type == eLoadType.管理部门QS)
            {
                dt = BusinessTool.GetTextAndValue(
                    "QS_JX_BUMENXX", "S_BUMENMC", "S_BUMENBH", spit, "S_BUMENBH NOT IN('0','600')", "S_BUMENBH"
                ).Tables[0];
            }
            else if (type == eLoadType.行业分类QS)
            {
                dt = BusinessTool.GetTextAndValue(
                    "QS_JX_HANGYEFLXX", "S_FENLEIMC", "S_FENLEIBH", spit, "I_JLZT=0", "S_FENLEIBH"
                ).Tables[0];
            }
            else if (type == eLoadType.行政区QS)
            {
                dt = BusinessTool.GetTextAndValue(
                    "QS_JX_XINGZHENGQ", "S_XINGZHENGQM", "S_XINGZHENGQH", spit, "I_JLZT=0", "S_XINGZHENGQH"
                ).Tables[0];
            }
            else if (type == eLoadType.环线标记QS)
            {
                dt = new DataTable();
                dt.Columns.Add("TEXT");
                dt.Columns.Add("VALUE");
                dt.Rows.Add("外环线内", "1");
                dt.Rows.Add("外环线外", "2");
            }
            else if (type == eLoadType.流域QS)
            {
                dt = BusinessTool.GetTextAndValue(
                    "QS_JX_LIUYUXX", "S_LIUYUMC", "S_LIUYUBH", spit, "I_JLZT=0", "S_LIUYUBH"
                ).Tables[0];
            }
            else if (type == eLoadType.取水用途QS)
            {
                dt = BusinessTool.GetTextAndValue(
                    "QS_JX_QUSHUIXX", "S_QUSHUIMC", "S_QUSHUIBH", spit, "I_JLZT=0", "S_QUSHUIBH"
                ).Tables[0];
            }
            else if (type == eLoadType.水利分片QS)
            {
                dt = BusinessTool.GetTextAndValue(
                    "QS_JX_SHUILIFPXX", "S_SHUILIFPMC", "S_SHUILIFPBH", spit, "I_JLZT=0", "S_SHUILIFPBH"
                ).Tables[0];
            }
            else if (type == eLoadType.水资源分区QS)
            {
                dt = BusinessTool.GetTextAndValue(
                    "QS_JX_SHUIZIYFQ", "S_SHUIZIYMC", "S_SHUIZIYBH", spit, "I_JLZT=0", "S_SHUIZIYBH"
                ).Tables[0];
            }
            else if (type == eLoadType.井标记QS)
            {
                dt = BusinessTool.GetTextAndValue(
                    "QS_JX_JINGBIAOJXX", "S_YUZHIMC", "S_YUZHIBH", spit, "I_JLZT=0", "S_YUZHIBH"
                ).Tables[0];
            }
            else if (type == eLoadType.业务员QS)
            {
                //dt = new DataTable();
                //dt.Columns.Add("TEXT");
                //dt.Columns.Add("VALUE");
                //dt.Rows.Add("袁培玲", "1");
                //dt.Rows.Add("秦福祥", "2");
                dt = BusinessTool.GetTextAndValue(
                    "view_as_userinfo", "USERNAME", "USERID", spit,
                    "departmentname='取水科' and ROLEID=" + (BusinessTool.WType == 1 ? "100023" : "100022")
                ).Tables[0];
            }
            else if (type == eLoadType.水量类别QS)
            {
                dt = new DataTable();
                dt.Columns.Add("TEXT");
                dt.Columns.Add("VALUE");
                dt.Rows.Add("普通采", "1");
                dt.Rows.Add("采灌采", "2");
                dt.Rows.Add("采灌灌", "3");
                dt.Rows.Add("矿泉采", "4");
                dt.Rows.Add("专灌", "5");
            }
            else if (type == eLoadType.井类型QS)
            {
                dt = new DataTable();
                dt.Columns.Add("TEXT");
                dt.Columns.Add("VALUE");
                dt.Rows.Add("常用井", "1");
                dt.Rows.Add("采灌井", "2");
                dt.Rows.Add("专灌井", "3");
                dt.Rows.Add("矿泉井", "4");
            }
            else if (type == eLoadType.井性质QS)
            {
                dt = new DataTable();
                dt.Columns.Add("TEXT");
                dt.Columns.Add("VALUE");
                dt.Rows.Add("空状态", "1");
                dt.Rows.Add("备用井", "2");
                dt.Rows.Add("更新报废井", "3");
                dt.Rows.Add("更新井", "4");
                dt.Rows.Add("报废井", "5");
                dt.Rows.Add("填没井", "6");
                dt.Rows.Add("注销许可证", "7");
                dt.Rows.Add("注销井恢复使用", "8");
            }
            else if (type == eLoadType.费用类型QS)
            {
                dt = new DataTable();
                dt.Columns.Add("TEXT");
                dt.Columns.Add("VALUE");
                dt.Rows.Add("开采井水费", "0");
                dt.Rows.Add("加价", "1");
                //dt.Rows.Add("采灌补收", "3");
            }
            else if (type == eLoadType.退款类型QS)
            {
                dt = new DataTable();
                dt.Columns.Add("TEXT");
                dt.Columns.Add("VALUE");
                dt.Rows.Add("多收退款", "1");
                dt.Rows.Add("收错退款", "2");
                dt.Rows.Add("调整退款", "3");
            }
            else
            {
                dt = new DataTable();
            }
            if (all != null)
            {
                var drTemp = dt.NewRow();
                drTemp[0] = all;
                drTemp[1] = "-1";
                dt.Rows.InsertAt(drTemp, 0);
            }
            BindComboBox(
                cmb, dt
            );
            if (cmb.Items.Count > 0)
                cmb.SelectedIndex = 0;
        }

        #region 文件上传

        public static string GetUploadPath(int wtype, string urltype)
        {
            var uploadDirectory = (wtype == 0)? "/Upload/ZLS/"
                                    : wtype == 1? "/Upload/DBS/"
                                    : wtype == 2? "/Upload/DXS/"
                                    : "/Upload/QT/";
            uploadDirectory = uploadDirectory +
                              (urltype.ToUpper() == "LH" ? "LH/" : urltype.ToUpper() == "YHZL" ? "YHZLSC/" : "QT/");
            var accpath = HttpContext.Current.Server.MapPath(uploadDirectory);
            if (!Directory.Exists(accpath))
                Directory.CreateDirectory(accpath);
            return uploadDirectory;
        }
        public static string GetUploadTempPath()
        {
            var uploadDirectory = "/UploadTemp/";
            var accpath = HttpContext.Current.Server.MapPath(uploadDirectory);
            if (!Directory.Exists(accpath))
                Directory.CreateDirectory(accpath);
            return uploadDirectory;
        }

        #endregion

        #region 获取站点 管理块

        public static void GetLHDJZDGLKYWY(string yhh, out string zd, out string glk, out string ywy)
        {
            if (BusinessTool.WType != 0)
            {
                zd = null;
                glk = null;
                if (string.IsNullOrEmpty(yhh))
                {
                    ywy = "111";
                }
                else
                {
                    var dt = BusinessTool.GetTextAndValue("QS_YG_YONGHUXX", "S_YEWUY", "S_YEWUY", null,
                        "I_WTYPE=" + BusinessTool.WType + " AND S_YONGHUH='" + yhh + "'").Tables[0];
                    ywy = dt.Rows[0]["TEXT"].ToString();
                }
            }
            else
            {
                //var dt = BusinessTool.GetTextAndValueAndSelectColumns("YS_YG_YONGHUXX", "S_ZHANDIANBH", "S_GUANLIKBH",
                //    "S_YEWUY", null, "I_JLZT=0 AND I_LEIXING=1 AND S_YONGHUH='" + yhh + "'", null).Tables[0];
                var dt = BusinessTool.GetTextAndValueAndSelectColumns("YS_YG_YONGHUXX", "S_ZHANDIANBH", "S_GUANLIKBH",
                    "S_YEWUY", null, "I_LEIXING=1 AND S_YONGHUH='" + yhh + "'", null).Tables[0];
                zd = dt.Rows[0]["TEXT"].ToString();
                glk = dt.Rows[0]["VALUE"].ToString();
                ywy = dt.Rows[0]["S_YEWUY"].ToString();
            }
        }

        # endregion

        #region GRIDVIEW获取,设置选中

        /// <summary>
        ///     复制GRIDVIEW中选中的数据到新的datatable
        /// </summary>
        /// <param name="gv">GRIDVIEW</param>
        /// <param name="dtSource">GRIDVIEW关联的数据源</param>
        public static DataTable GetCheckedData(ASPxGridView gv, DataTable dtSource, string checkboxid,
            string hiddenfieldid)
        {
            var dt = dtSource.Clone();
            var list = GetCheckedValueList(gv, checkboxid, hiddenfieldid);
            foreach (var key in list.Keys)
                for (var i = 0; i < dtSource.Rows.Count; i++)
                    if (dtSource.Rows[i]["ROWNUM"].ToString() == key)
                    {
                        var rowT = dt.NewRow();
                        for (var j = 0; j < rowT.Table.Columns.Count; j++)
                            rowT[j] = dtSource.Rows[i][j];
                        dt.Rows.Add(rowT);
                        break;
                    }
            return dt;
        }


        /// <summary>
        ///     获取选中项指定值
        /// </summary>
        public static Dictionary<string, string> GetCheckedValueList(ASPxGridView gv, string checkboxid,
            string hiddenfieldid)
        {
            var list = new Dictionary<string, string>();
            for (var i = 0; i < gv.VisibleRowCount; i++)
            {
                var cb = (ASPxCheckBox) gv.FindRowCellTemplateControl(i, (GridViewDataColumn) gv.Columns[0],
                    checkboxid);
                if (cb.Checked)
                {
                    var hid = (HiddenField) gv.FindRowCellTemplateControl(i, (GridViewDataColumn) gv.Columns[0],
                        hiddenfieldid);
                    list.Add(hid.Value, hid.Value);
                }
            }
            return list;
        }

        /// <summary>
        ///     重新设置GRIDVIEW 选中项
        /// </summary>
        public static void SetCheckedValueList(ASPxGridView gv, string checkboxid, string hiddenfieldid,
            Dictionary<string, string> list)
        {
            if (list.Count == 0)
                return;
            for (var i = 0; i < gv.VisibleRowCount; i++)
            {
                var cb = (ASPxCheckBox) gv.FindRowCellTemplateControl(i, (GridViewDataColumn) gv.Columns[0],
                    checkboxid);
                cb.Checked = false;
            }
            for (var i = 0; i < gv.VisibleRowCount; i++)
            {
                var cb = (ASPxCheckBox) gv.FindRowCellTemplateControl(i, (GridViewDataColumn) gv.Columns[0],
                    checkboxid);
                var hid = (HiddenField) gv.FindRowCellTemplateControl(i, (GridViewDataColumn) gv.Columns[0],
                    hiddenfieldid);
                if (list.ContainsKey(hid.Value))
                    cb.Checked = true;
            }
        }

        /// <summary>
        ///     设置GRIDVIEW 全选
        /// </summary>
        public static void SetCheckedAll(ASPxGridView gv, string checkboxid, bool check)
        {
            for (var i = 0; i < gv.VisibleRowCount; i++)
            {
                var cb = (ASPxCheckBox) gv.FindRowCellTemplateControl(i, (GridViewDataColumn) gv.Columns[0],
                    checkboxid);
                cb.Checked = check;
            }
        }

        #endregion
    }
}